// 在文件顶部添加类型声明
declare function acquireVsCodeApi(): {
    postMessage(message: any): void;
    getState(): any;
    setState(state: any): void;
};

// 声明全局 vscode 变量
let vscode: {
    postMessage(message: any): void;
    getState(): any;
    setState(state: any): void;
};

// 在 DOMContentLoaded 事件之前初始化 vscode
try {
    vscode = acquireVsCodeApi();
} catch (e) {
    console.error('Failed to acquire VS Code API', e);
}

// 定义消息处理函数
function updateLastMessage(content: string, type: string) {
    console.log('Updating message:', { content, type });
    const messagesContainer = document.getElementById('messages');
    if (!messagesContainer) {
        console.error('Messages container not found');
        return;
    }
    
    let lastMessage = messagesContainer.lastElementChild;
    console.log('Last message:', lastMessage);
    
    // 如果没有最后一条消息或最后一条是用户消息，创建新的 AI 消息
    if (!lastMessage || lastMessage.classList.contains('user-message')) {
        lastMessage = document.createElement('div');
        lastMessage.className = 'message assistant-message';
        
        const avatar = document.createElement('div');
        avatar.className = 'message-avatar';
        avatar.textContent = 'AI';
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        
        // 创建响应内容容器
        const responseDiv = document.createElement('div');
        responseDiv.className = 'response-content';
        messageContent.appendChild(responseDiv);
        
        // 创建推理内容容器
        const reasoningDiv = document.createElement('div');
        reasoningDiv.className = 'reasoning-content';
        messageContent.appendChild(reasoningDiv);
        
        lastMessage.appendChild(avatar);
        lastMessage.appendChild(messageContent);
        messagesContainer?.appendChild(lastMessage);
    }
    
    // 更新消息内容
    const messageContent = lastMessage.querySelector('.message-content');
    if (messageContent) {
        if (type === 'reasoning') {
            const reasoningDiv = messageContent.querySelector('.reasoning-content');
            if (reasoningDiv) {
                reasoningDiv.textContent = content;
                console.log('Updated reasoning content:', reasoningDiv.textContent);
            } else {
                console.error('Reasoning div not found');
            }
        } else {
            const responseDiv = messageContent.querySelector('.response-content');
            if (responseDiv) {
                responseDiv.textContent = (responseDiv.textContent || '') + content;
                console.log('Updated response content:', responseDiv.textContent);
            } else {
                console.error('Response div not found');
            }
        }
    } else {
        console.error('Message content div not found');
    }
    
    // 滚动到底部
    messagesContainer?.scrollTo({
        top: messagesContainer.scrollHeight,
        behavior: 'smooth'
    });
}

function addNewMessage(message: string, isUser: boolean, reasoning?: string, isStreaming: boolean = false) {
    const messagesContainer = document.getElementById('messages');
    if (!messagesContainer) {
        console.error('Messages container not found');
        return;
    }

    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isUser ? 'user-message' : 'assistant-message'}`;
    
    // 如果是流式消息，立即添加 streaming 类
    if (isStreaming) {
        messageDiv.classList.add('streaming');
    }
    
    // 创建头像
    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    avatar.textContent = isUser ? '👤' : 'AI';
    
    // 创建消息内容容器
    const contentContainer = document.createElement('div');
    contentContainer.className = 'message-content';
    
    // 添加消息头部
    const header = document.createElement('div');
    header.className = 'message-header';
    header.textContent = isUser ? '你' : 'DeepSeek Assistant';
    contentContainer.appendChild(header);
    
    // 添加消息文本容器
    const messageText = document.createElement('div');
    messageText.className = 'message-text';
    
    // 创建响应内容容器
    const responseDiv = document.createElement('div');
    responseDiv.className = 'response-content';
    // 关键修改：只有在非流式消息时才设置初始内容
    if (!isStreaming) {
        responseDiv.textContent = message;
    }
    messageText.appendChild(responseDiv);
    
    // 如果有推理内容，添加推理容器
    if (reasoning) {
        const reasoningDiv = document.createElement('div');
        reasoningDiv.className = 'reasoning-content';
        reasoningDiv.textContent = reasoning;
        messageText.appendChild(reasoningDiv);
    }
    
    contentContainer.appendChild(messageText);
    messageDiv.appendChild(avatar);
    messageDiv.appendChild(contentContainer);
    
    // 添加到容器
    messagesContainer.appendChild(messageDiv);
    
    // 滚动到底部
    requestAnimationFrame(() => {
        messagesContainer.scrollTo({
            top: messagesContainer.scrollHeight,
            behavior: 'smooth'
        });
    });

    // 返回创建的消息元素
    return messageDiv;
}

function updateStreamMessage(content: string, type: string) {
    console.log('Updating stream message:', { content, type });
    
    const messagesContainer = document.getElementById('messages');
    if (!messagesContainer) {
        console.error('Messages container not found');
        return;
    }

    const lastMessage = messagesContainer.lastElementChild as HTMLElement;
    if (!lastMessage || !lastMessage.classList.contains('assistant-message')) {
        console.error('No assistant message found to update');
        return;
    }

    // 确保消息有 streaming 类
    lastMessage.classList.add('streaming');

    const responseDiv = lastMessage.querySelector('.response-content') as HTMLElement;
    if (!responseDiv) {
        console.error('Response div not found');
        return;
    }

    // 更新内容
    if (type === 'reasoning') {
        const reasoningDiv = lastMessage.querySelector('.reasoning-content') as HTMLElement;
        if (reasoningDiv) {
            reasoningDiv.textContent = content;
        }
    } else {
        // 更新内容并保持光标
        const tempDiv = document.createElement('div');
        tempDiv.textContent = content;
        
        // 如果内容不同，才更新
        if (responseDiv.textContent !== content) {
            // 保存滚动位置
            const wasAtBottom = messagesContainer.scrollHeight - messagesContainer.scrollTop === messagesContainer.clientHeight;
            
            // 更新内容
            responseDiv.textContent = content;
            
            // 如果之前在底部，滚动到底部
            if (wasAtBottom) {
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
        }
    }
}

// 修改 CSS 样式
const style = document.createElement('style');
style.textContent = `
    .message.streaming .response-content {
        position: relative;
        min-height: 20px;
    }

    .message.streaming .response-content::after {
        content: '▋';
        display: inline-block;
        animation: blink 0.7s steps(1) infinite;
        margin-left: 2px;
        color: var(--vscode-editor-foreground);
        vertical-align: middle;
        position: relative;
        top: -1px;
    }

    @keyframes blink {
        50% { opacity: 0; }
    }

    .message {
        display: flex;
        gap: 12px;
        padding: 12px;
        margin: 8px 0;
        opacity: 1;
        transition: opacity 0.3s ease;
    }

    .message.streaming {
        animation: fadeIn 0.3s ease;
    }

    .message-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .response-content,
    .reasoning-content {
        white-space: pre-wrap;
        word-break: break-word;
        line-height: 1.5;
        min-height: 1.5em;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
`;
document.head.appendChild(style);

// 修改 sendMessage 函数
function sendMessage() {
    if (!vscode) {
        console.error('VS Code API not available');
        return;
    }

    const messageInput = document.getElementById('messageInput') as HTMLTextAreaElement;
    const modelSelector = document.getElementById('modelSelector') as HTMLSelectElement;
    const text = messageInput.value.trim();
    const model = modelSelector.value;

    if (text) {
        console.log('Sending message to extension:', { text, model });
        vscode.postMessage({
            command: 'sendMessage',
            text: text,
            model: model
        });
        messageInput.value = '';
        // 重置输入框高度
        messageInput.style.height = 'auto';
    }
}

// 修改消息处理监听器
window.addEventListener('message', event => {
    const message = event.data;
    console.log('Received message in webview:', message);
    
    switch (message.command) {
        case 'addMessage':
            console.log('Adding new message:', message);
            if (message.isUser) {
                // 用户消息直接添加
                addNewMessage(message.message, true, undefined, false);
            } else if (message.isStreaming) {
                // 流式 AI 消息，创建空容器并开始流式输出
                console.log('Creating streaming message container');
                const messageDiv = addNewMessage('', false, undefined, true);
                // 立即开始更新第一条内容
                if (message.message) {
                    updateStreamMessage(message.message, 'response');
                }
            } else {
                // 非流式 AI 消息
                addNewMessage(message.message, false, message.reasoning, false);
            }
            break;
        case 'updateStreamMessage':
            console.log('Updating stream message:', message);
            updateStreamMessage(message.content, message.type);
            break;
        case 'finishStreaming':
            console.log('Finishing streaming');
            const lastMessage = document.querySelector('.message.streaming');
            if (lastMessage) {
                lastMessage.classList.remove('streaming');
            }
            break;
        case 'updateGenerating':
            console.log('Updating generating state:', message.isGenerating);
            const stopButton = document.getElementById('stop-button');
            if (stopButton) {
                stopButton.style.display = message.isGenerating ? 'block' : 'none';
            }
            break;
        case 'showError':
            console.error('Error:', message.message);
            break;
        default:
            console.log('Unknown command:', message.command);
    }
});

// 修改 DOMContentLoaded 事件处理
document.addEventListener('DOMContentLoaded', () => {
    // 不再需要在这里初始化 vscode
    
    // 添加事件监听器
    document.getElementById('sendButton')?.addEventListener('click', sendMessage);
    document.getElementById('messageInput')?.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
}); 